<template>
	<view class="u-page">
		<!--#ifndef H5-->
		<u-navbar title="一键配网" @rightClick="rightClick" autoBack>
			 <view class="u-nav-slot" slot="left"></view>
		</u-navbar>
		<!--#endif-->
		<view class="bg-contaniner"></view>
		<view class="content">
			<u-subsection :list="list" mode="subsection" fontSize="18" :current="curNow" @change="sectionChange" ></u-subsection>
			<view class="sub-content state" :style="{minHeight:deviceInfo.deviceName?'auto':'445px'}" v-if="curNow==0">
				<u-cell title="设备状态" class="title" size="large">
					<u-loading-icon slot="right-icon" v-if="statusing"></u-loading-icon>
					<u-icon slot="right-icon" name="reload" size="24" v-else @click="getDeviceInfo"></u-icon>
				</u-cell>
				<scroll-view scroll-y refresher-enabled refresher-background="#64abf5" @refresherrefresh="getDeviceInfo" @refresherpulling="getDeviceInfoTriggered=true" :refresher-threshold="60" :refresher-triggered="getDeviceInfoTriggered">
					<u-cell-group v-if="deviceInfo.deviceName">
						<u-cell title="设备名称" :value="deviceInfo.deviceName"></u-cell>
						<u-cell title="固件版本" :value="deviceInfo.deusitWifiVersion"></u-cell>
						<u-cell title="SDK版本" :value="deviceInfo.sdkVersion"></u-cell>
						<u-cell title="开机时间" :value="deviceInfo.runTime"></u-cell>
						<u-cell title="内存" :value="deviceInfo.flashChipRealSize"></u-cell>
						<u-cell title="WIFI模式" :value="deviceInfo.wifiMode"></u-cell>
						<u-cell title="SSID" :value="deviceInfo.wifiSSID" v-if="deviceInfo.wifiSSID"></u-cell>
						<u-cell title="RSSI" :value="deviceInfo.wifiRSSI" v-if="deviceInfo.wifiRSSI"></u-cell>
						<u-cell title="IP地址" :value="deviceInfo.wifiLocalIP" v-if="deviceInfo.wifiLocalIP"></u-cell>
					</u-cell-group>
					<u-collapse v-if="deviceInfo.deviceName" :border="false">
						<u-collapse-item title="其他信息" name="deviceInfoOther" class="title" size="large">
							<u-cell-group>
								<u-cell title="核心库版本" :value="deviceInfo.coreVersion"></u-cell>
								<u-cell title="芯片ID" :value="deviceInfo.chipId"></u-cell>
								<u-cell title="芯片STA-MAC地址" :value="deviceInfo.macAddress"></u-cell>
								<u-cell title="芯片AP-MAC地址" :value="deviceInfo.softAPmacAddress"></u-cell>
								<u-cell title="可用堆大小" :value="deviceInfo.freeHeap"></u-cell>
								<u-cell title="CPU运行频率" :value="deviceInfo.cpuFreqMHz"></u-cell>
								<u-cell title="当前固件大小" :value="deviceInfo.sketchSize"></u-cell>
								<u-cell title="剩余可用固件空间" :value="deviceInfo.freeSketchSpace"></u-cell>
								<u-cell title="闪存芯片ID" :value="deviceInfo.flashChipId"></u-cell>
								<u-cell title="闪存芯片模式" :value="deviceInfo.flashChipMode"></u-cell>
								<u-cell title="闪存芯片真正大小" :value="deviceInfo.flashChipRealSize"></u-cell>
								<u-cell title="闪存芯片运行频率" :value="deviceInfo.flashChipSpeed"></u-cell>
							</u-cell-group>
						</u-collapse-item>
					</u-collapse>
				</scroll-view>
				<view v-if="!deviceInfo.deviceName" @click="getDeviceInfo">
					<u-loading-icon :show="statusing" mode="semicircle" text="加载中" size="60" textSize="18" vertical style="margin-top: 120px;"></u-loading-icon>
					<u-empty :show="!statusing" mode="list" text="获取信息失败" marginTop="100" textSize="18"></u-empty>
				</view>
			</view>
			
			<block v-if="curNow==1">
				<view class="sub-content wifi" v-if="wifiConnected.ssid">
					<view class="busy" v-if="wifiConnected.busy"></view>
					<u-cell icon="wifi" :title="wifiConnected.ssid" :label="wifiConnected.busy?'正在验证身份...':('已连接 '+(wifiConnected.ip?wifiConnected.ip:''))" :name="wifiConnected.ssid" :value="wifiConnected.busy?'连接中':'已连接'" size="large" clickable></u-cell>
				</view>
				<view class="sub-content" :style="{height:wifiConnected.ssid&&wifiList.length?'auto':'70vh'}">
					<u-cell title="选取附近的WLAN" class="title" size="large">
						<u-loading-icon slot="right-icon" show v-if="freshing"></u-loading-icon>
						<u-icon slot="right-icon" name="reload" size="24" v-else @click="refreshWifi"></u-icon>
					</u-cell>
					<scroll-view :style="{maxHeight:wifiConnected.ssid&&wifiList.length?'50vh':'70vh'}" scroll-y refresher-enabled refresher-background="#64abf5" @refresherrefresh="refreshWifi" @refresherpulling="refreshWifiTriggered=true" :refresher-threshold="60" :refresher-triggered="refreshWifiTriggered">
						<u-cell-group v-if="wifiList.length">
							<template v-for="(item, index) in wifiList">
								<u-cell icon="wifi" :title="item.ssid" :name="index" size="large" isLink @click="connectWifi">
									<u-icon slot="value" name="lock-fill" v-if="item.encryptionType!='Open'"></u-icon>
								</u-cell>
							</template>
						</u-cell-group>
						<view v-else @click="refreshWifi">
							<u-loading-icon :show="freshing" mode="semicircle" text="加载中" size="60" textSize="18" vertical style="margin-top: 20vh;"></u-loading-icon>
							<u-empty :show="!freshing" mode="wifi" text="获取WALN失败" marginTop="20vh" textSize="18" ></u-empty>
						</view>
					</scroll-view>
				</view>
				<u-modal :show="wifiConnect.enterPwd" :title="wifiConnect.ssid" showCancelButton closeOnClickOverlay @confirm="confirmWifiPwd" @cancel="wifiConnect={}" @close="wifiConnect={}" :confirmColor="wifiConnectPwd.length>7?'#2979ff':'#ddd'">
					<u--input slot="default" border="surround" clearable prefixIcon="lock" placeholder="WIFI密码" password :focus="wifiConnect.enterPwd" v-model="wifiConnectPwd" ></u--input>
				</u-modal>
			</block>
			
			<view class="sub-content mqtt" v-if="curNow==2">
				<u-cell title="设置MQTT" class="title" size="large">
					<u-loading-icon slot="right-icon" v-if="mqtting"></u-loading-icon>
					<u-icon slot="right-icon" name="reload" size="24" v-else @click="refreshMqtt"></u-icon>
				</u-cell>
				
				<scroll-view scroll-y refresher-enabled refresher-background="#64abf5" @refresherrefresh="refreshMqtt" @refresherpulling="refreshMqttTriggered=true" :refresher-threshold="60" :refresher-triggered="refreshMqttTriggered">
					<u--form :model="mqtt" ref="mqttForm" class="mqtt-form" labelWidth="100" labelAlign="right" :rules="mqttRules">
						<u-form-item label="地址" prop="host" borderBottom>
							<u-input v-model="mqtt.host" border="none" placeholder="192.168.8.8" clearable/>
						</u-form-item>
						<u-form-item label="端口" prop="mqtt.port" borderBottom>
							<u-input v-model="mqtt.port" border="none" placeholder="1883" type="integer" clearable/>
						</u-form-item>
						<u-form-item label="路径" prop="mqtt.path" borderBottom>
							<u-input v-model="mqtt.path" border="none" placeholder="/mqtt" clearable/>
						</u-form-item>
						<u-form-item label="用户名" prop="mqtt.username" borderBottom>
							<u-input v-model="mqtt.username" border="none" placeholder="用户名" clearable/>
						</u-form-item>
						<u-form-item label="密码" prop="mqtt.password" borderBottom>
							<u-input v-model="mqtt.password" border="none" placeholder="密码" password clearable/>
						</u-form-item>
						<u-form-item label="主题" prop="mqtt.topic" borderBottom>
							<u-input v-model="mqtt.topic" border="none" placeholder="topic" clearable/>
						</u-form-item>
						<u-form-item label="保持" prop="mqtt.retain" borderBottom>
							<u-switch v-model="mqtt.retain" activeColor="#3c9cff"></u-switch>
						</u-form-item>
						<u-form-item label="状态" borderBottom>
							<u--text :type="mqtt.status==1?'primary':'info'" :text="mqtt.submit?'保存中...':mqtt.status==1?'已连接':'未连接'" size="20"></u--text>
						</u-form-item>
					</u--form>
					<u-button @click="submitMqtt" type="primary" :loading="mqtting || mqtt.submit" :loadingText="mqtting?'获取中...':'保存中...'" size="large" :disabled="!mqtt.host">保存</u-button>
				</scroll-view>
			</view>
			<block v-if="curNow==3">
				<view class="sub-content other">
					<u-cell title="OTA更新" class="title" size="large">
						<u-loading-icon slot="right-icon" v-if="mqtting"></u-loading-icon>
						<u-icon slot="right-icon" name="reload" size="24" v-else @click="refreshMqtt"></u-icon>
					</u-cell>
				</view>
				<view class="sub-content other">
					<u-cell title="固件升级" class="title" size="large"></u-cell>
					<view>
						<u-upload
							accept="file"
							:fileList="fileList1"
							name="1"
							multiple
							:maxCount="10"
						></u-upload>
					</view>
				</view>
				<view class="sub-content other">
					<u-cell title="其他设置" class="title" size="large"></u-cell>
					<view>
						<u-cell title="隐藏AP" class="title">
							<u-switch slot="right-icon" v-model="deviceInfo.wifiHide" activeColor="#3c9cff" :loading="hideWifiing" @change="hideWifi"></u-switch>
						</u-cell>
					</view>
				</view>
			</block>
			<view class="sub-content about" v-if="curNow==4">
				<u-icon name="wifiheart" size="60" labelSize="18" label="Deusit_WIFI" labelPos="bottom" @click="easterShow" color="#2196f3"></u-icon>
			</view>
		</view>
		<view class="easter" v-if="easter" @click="easterHide"><view class="ghost"></view></view>
		<u-modal :show="modalContent?true:false" :title="modalTitle" :content='modalContent' @confirm="modalContent=''"></u-modal>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import { deviceInfo, wifiConfig, wifiScan, mqttRefresh, mqttSubmit, opera } from '@/common/api.js';
	export default {
		data() {
			return {
				list: ['状态', '网络', 'MQTT', '其他', '关于'],
				curNow: 3,
				getDeviceInfoTriggered: false,
				refreshWifiTriggered: false,
				refreshMqttTriggered: false,
				statusing: false,
				freshing: false,
				mqtting: false,
				hideWifiing: false,
				deviceInfo: {},
				wifiList: [],
				wifiConnect: {},
				wifiConnected: {},
				wifiConnectPwd: "",
				mqtt: {
					host: '',
					port: '',
					path: '',
					username: '',
					password: '',
					topic: '',
					retain: false,
					status: false,
					submit: false,
				},
				mqttRules: {
					host: {
						type: 'string',
						required: true,
						message: '请填写MQTT地址',
						trigger: ['blur']
					},
				},
				modalTitle: "",
				modalContent: "",
				// EGG
				lastTime: 0,
				count: 0,
				easter: false,
			}
		},
		onLoad() {
			// 进入后自动获取WIFI
			//this.getDeviceInfo();
		},
		methods: {
			sectionChange(index) {
				this.curNow = index;
				//index==1 && this.wifiList.length==0 && this.refreshWifi();
			},
			// 获取设备参数
			getDeviceInfo() {
				if(this.statusing) return;
				this.getDeviceInfoTriggered || (this.deviceInfo = {});
				this.statusing = true;
				deviceInfo({timeout: 10000}).then((res)=>{
					this.getDeviceInfoTriggered = false;
					this.statusing = false;
					this.deviceInfo = res.data;
					this.deviceInfo['runTime'] = uni.$u.timeFormat(Date.now() - this.deviceInfo['bootTime'], "yyyy-mm-dd hh:MM");
					if(res.data.wifiSSID){
						this.wifiConnected = {ssid:res.data.wifiSSID,ip:res.data.wifiLocalIP};
					}
					if(res.data.mqtt){
						this.mqtt = res.data.mqtt;
					}
				}).catch((err) =>{
					this.statusing = false;
					console.error("/deviceInfo", err);
					this.modalContent = err.errMsg;
				})
			},
			// 刷新WIFI列表
			refreshWifi() {
				if(this.freshing) return;
				this.refreshWifiTriggered || (this.wifiList = []);
				this.freshing = true;
				wifiScan().then((res)=>{
					this.wifiList = res.data;
					this.refreshWifiTriggered = false;
					this.freshing = false;
				}).catch((err) =>{
					this.freshing = false;
					console.error("/refreshWifi", err);
					this.modalContent = err.errMsg;
				})
			},
			// 连接WIFI
			connectWifi(obj) {
				this.wifiConnect = this.wifiList[obj.name];
				this.wifiConnectPwd = "";
				if(this.wifiConnect.encryptionType == "Open"){
					this.confirmWifiPwd()
				}else{
					this.wifiConnect.enterPwd = true;
				}
			},
			// 配置连接WIFI密码
			confirmWifiPwd() {
				if(this.wifiConnect.encryptionType != "Open" && this.wifiConnectPwd.length<7){
					return false;
				}
				this.wifiConnect.enterPwd = false;
				this.wifiConnected = {...this.wifiConnect,pwd:this.wifiConnectPwd,busy:1}
				wifiConfig({ssid: this.wifiConnect.ssid, password: this.wifiConnectPwd}).then((res)=>{
					this.wifiConnected.busy = 0;
					if(res.status){
						this.wifiConnected.ip = res.data.ip;
					}else{
						this.modalContent = res.msg;
					}
				}).catch((err) =>{
					this.wifiConnected.busy = 0
					console.error("/wifiConfig", err);
					this.modalContent = err.errMsg;
				})
			},
			// 刷新MQTT配置
			refreshMqtt() {
				if(this.mqtting) return;
				this.mqtting = true;
				mqttRefresh().then((res)=>{
					this.mqtt = res.data;
					this.refreshMqttTriggered = false;
					this.mqtting = false;
				}).catch((err) =>{
					this.mqtting = false;
					console.error("/refreshMqtt", err);
					this.modalContent = err.errMsg;
				})
			},
			// 保存MQTT配置
			submitMqtt() {
				if(this.mqtt.submit) return;
				this.mqtt.submit = true;
				this.$forceUpdate();	//强制更新
				mqttSubmit(this.mqtt).then((res)=>{
					uni.$u.toast(res.msg+"，5秒后自动刷新状态");
					setTimeout(()=>{
					    this.refreshMqtt();
					}, 5000);
					this.mqtt.submit = false;
				}).catch((err) =>{
					this.mqtt.submit = false;
					console.error("/submitMqtt", err);
					this.modalContent = err.errMsg;
				})
			},
			// 隐藏WIFI
			hideWifi() {
				this.hideWifiing = true;
				opera({act:'setConfig',state:this.deviceInfo.wifiHide?2:1}).then((res)=>{
					this.hideWifiing = false;
				}).catch((err) =>{
					this.hideWifiing = false;
					console.error("/hideWifi", err);
					this.modalContent = err.errMsg;
				})
			},
			easterShow() {
				if(this.count > 3){
					this.easter = true;
					setTimeout(()=>{
					    this.count = 0;
					}, 3000);
				}else{
					var currentTime = new Date().getTime();
					this.count = (currentTime-this.lastTime) < 1000 ? this.count + 1 : 1;
					this.lastTime = currentTime;
				}
			},
			easterHide() {
				if(this.count == 0){
					this.easter = false;
				}
			}
			
		}
	}
</script>

<style lang="scss">
	/* 通用 START */
	.content {
		padding: 44px 20px;
		max-width: 850px;
		margin: auto;
	}
	
	/deep/ .u-subsection{
		border-radius: 10px;
		background: #fff;
		box-shadow: 0 0 10px #fff;
		height: 50px;
		&__item {
			&__text{
				font-size: 20px !important;
			}
			&--first {
				border-top-left-radius: 10px;
				border-bottom-left-radius: 10px;
			}
			&--last {
				border-top-right-radius: 10px;
				border-bottom-right-radius: 10px;
			}
		}
	}
	
	/deep/ .u-cell__title-text--large {
		font-size: 20px !important;
	}
	
	.sub-content {
		margin-top: 30px;
		background: #fff;
		box-shadow: 0 0 10px #fff;
		border-radius: 10px;
		overflow: hidden;
		position: relative;
		.title {
			color: $u-tips-color;
			background-color: $u-bg-color;
			font-size: 20px;
		}
	}
	/* 通用  END  */
	
	
	/* 状态 START */
	.state{
		/deep/ .u-collapse-item__content__text{
			padding: 0;
			background: #fff;
		}
		
		/deep/ .u-cell__title-text, /deep/ .u-cell__value{
			font-size: 18px;
		}
	}
	/* 状态  END  */
	
	/* 网络 START */
	.wifi{
		background: $u-primary;
		min-height: auto;
		
		/deep/ .u-cell--clickable{
			background: $u-primary-dark;
		}
		/deep/ uni-text{
			color: $u-primary-light !important;
		}
		/deep/ .u-cell__label{
			color: $u-primary-disabled !important;
		}
		
		.busy{
			height: 100%;
			position: absolute;
			animation: rotation 3s linear infinite;
			box-shadow: 0 0 60px 60px $u-primary-disabled;
		}
		
		@-webkit-keyframes rotation {
		    0% {
				transform: translateX(calc(0 - 60px));
		    }
		    33% {
				transform: translateX(calc(100vw + 60px));
		    }
		    100% {
				transform: translateX(calc(100vw + 60px));
		    }
		}
	}
	/* 网络  END  */
	
	/* MQTT  END  */
	.mqtt{
		.mqtt-form{
			padding:0 30px;
			/deep/ .u-form-item__body__left__content__label, /deep/ .u-input__content__field-wrapper__field{
				font-size: 20px !important;
			}
			
			/deep/ .u-form-item__body__right, /deep/ .u-form-item__body__right__message {
				padding-left: 10px;
			}
		}
	}
	/* MQTT  END  */
	
	/* 其他 START */
	.other{
		background: $u-primary;
		height: auto;
	}
	/* 其他 START */
	
	/* 关于 START */
	.about{
		display: grid;
		min-height: 70vh;
	}
	.easter {
		height: 100vh;
		width: 100vw;
		position: absolute;
		display: flex;
		top: 0;
		background: #000;
		color: #fff;
		filter: blur(3px) contrast(10);
		
		.ghost {
		    position: relative;
		    width: 80px;
		    height: 120px;
		    background: 
		        radial-gradient(circle at 60px 40px, #000, #000 7px, transparent 7px),
		        radial-gradient(circle at 40px 40px, #000, #000 7px, transparent 7px),
		        radial-gradient(circle at 50px 50px, #fff, #fff);
		    background-size: 100% 100%; 
		    background-repeat: no-repeat;
		    margin: auto;
		    border-radius: 40px 40px 60px 20px;
		    transform: skewX(-10deg);
		    animation: moveMain 2s infinite ease-out;
			&::before,
			&::after {
			    content: "";
			    position: absolute;
			    background: #fff;
			    border-radius: 50%;
			}
			
			&::before {
			    width: 20px;
			    height: 20px;
			    top: 50px;
			    left: -10px;
			    box-shadow: 0 0 0 1px #fff;
			    animation: move 2s infinite ease-in;
			}
			
			&::after {
			    width: 30px;
			    height: 25px;
			    top: 95px;
			    left: -10px;
			    box-shadow: 0 0 0 1px #fff;
			    animation: move2 2s infinite ease-in;
			}
		}
		@keyframes move {
		    80%,
		    100% {
		        box-shadow: -60px 0 0 .5px rgba(255, 255, 255, .5);
		    }
		}
		
		@keyframes move2 {
		    80%,
		    100% {
		        box-shadow: -100px 0 0 .5px rgba(255, 255, 255, .2);
		    }
		}
		
		@keyframes moveMain {
		    42% {
		        transform: skewX(-10deg) translate(40px, 0);
		    }
		}
	}
	/* 关于  END  */
	
	/* 背景 START */
	.bg-contaniner {
	    position: fixed;
	    top: 0rpx;
	    left: 0rpx;
	    --text-color: hsl(0 95% 60%);
	    --bg-color: hsl(0 0% 100%);
	    --bg-size: 750rpx;
	    height: 100%;
	    display: grid;
	    place-items: center;
	    place-content: center;
	    overflow: hidden;
	    background-color: #4392F4;
	    z-index: -1;
		&::before {
		    --size: 150vmax;
		    grid-area: body;
		    content: "";
		    inline-size: var(--size);
		    block-size: var(--size);
		    background-image: url("/static/images/health.png");
		    background-size: var(--bg-size);
		    background-repeat: repeat;
		    transform: rotate(0deg);
		    opacity: 0.15;
		    animation: bg 10s linear infinite;
		}
		
		@media (prefers-reduced-motion: reduce) {
		    .bg-contaniner::before {
		      animation-duration: 0s;
		    }
		}
		
		@keyframes bg {
		    to {
		      background-position: 0 calc(var(--bg-size) * -1);
		    }
		}
	}
	/* 背景  END  */
	
	
</style>
